<template>
  <view>
    <navBar :navbarData.sync="navbarData"></navBar>
    <view class="video_box">
      <video style="width:100%;height: 1334rpx;"
        src="https://100000063-1252208446.file.myqcloud.com/video/2023072189501.mp4" :show-play-btn="false"
        :show-progress="false" :autoplay="true" :controls="false" :loop="true" object-fit="cover" :muted="true"
        :enable-progress-gesture="false">
      </video>
    </view>
    <view class="magazine_title">
      <img style="width:100%;" mode="widthFix"
        src="https://100000063-1252208446.file.myqcloud.com/images/litha/litha-index/0804/magezine_title1.png" alt="" />
    </view>
    <view class="subscribe_btn" @click="handleSubscribeMagazine">
      <img style="width:100%;" mode="widthFix"
        src="https://100000063-1252208446.file.myqcloud.com/images/litha/litha-index/0804/subscribe_button1.png" alt="" />
    </view>
    <view class="arrow_bottom">
      <img style="width:100%;" mode="widthFix"
        src="https://100000063-1252208446.file.myqcloud.com/images/litha/litha-index/0804/arrow_bottom1.png" alt="">
    </view>
    <view class="magazine_box">
      <view v-for="(item,index) in magazineArray" :key="index" @click.stop="handleMagazineDetails(item)">
        <view v-if="index == 0" class="list_1">
          <img style="width:100%;" mode="widthFix" :src="item.coverImg" alt="" srcset="">
          <img class="drinking_tips" mode="widthFix"
            src="https://100000063-1252208446.file.myqcloud.com/images/litha/litha-index/0804/tips_text1.png">
        </view>
        <view v-else class="list_item">
          <img style="width:100%;" mode="widthFix" :src="item.coverImg" alt="" srcset="">
        </view>
      </view>
     <view class="list_item" v-if="magazineArray.length % 2 == 0">
        <img style="width:100%;" mode="widthFix" src="https://100000063-1252208446.file.myqcloud.com/images/litha/magazine/expect.png" alt="" srcset="">
      </view>
    </view>
    <register-widget ref="registerWidgetRef" location="litha-magazine" @finish="onRegisterWidgetFinish" />
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>

<script>
  import {
    magazineData
  } from "./jsonData.js";
  import NavBar from '@/components/common/navbar';
  import util from '@/utils/util';
  import api from '@/api/api';
  import {
    SEL_CLASS_CODE,
    SEL_ACTIVE_CODE,
    SYSTEM_INFO,
    USER_INFO,
    CUSTOMER_INFO,
    CUSTOMER_HOTFIX,
    CART_KEY,
    MERCHANT_INFO,
    USER_SPECICAL_INFO
  } from '@/utils/constant';
  import registerWidget from "@/components/register/register-widget.vue"
  import {
    lithLaunch
  } from '@/utils/litha_report';
  export default {
    components: {
      navBar: NavBar,
      registerWidget
    },
    data() {
      return {
        magazineArray: magazineData,
        // 组件所需的参数
        navbarData: {
          whiteIcon: 1,
          showSearchAndBack: 1,
          showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
          title: '杂志页面', //导航栏 中间的标题
          newLogo: uni.getStorageInfoSync('storeLogo'),
          isTopFixed: true
        },
        // 订阅活动id
        msgId: 219,  //219正式版  170测试版
        deviceHeight: 0,
        pageHeight:0,
        viewProgress: 0
      }
    },
    onLoad: async function(option) {
      if (api.environment == 'formal') {
        this.msgId = 219; //  正式环境订阅id
      } else if (api.environment == 'trial') {
        this.msgId = 170; //  测试环境订阅id
      }
    },
    async onShow() {
      getApp().cl_tracker.track('mini_program_view', {
        path: '/pages/litha-launch/magazine/index',
        pageName: 'Magazine页面',
        campaign:'SZSH_LITHA_LAUNCH-2023'
      })
      lithLaunch("mini_program_view", {
        path: '/pages/litha-launch/magazine/index',
        pageName: 'Magazine页面',
        campaign:'SZSH_LITHA_LAUNCH-2023'
      })
      // 神策埋点
      this.$commonSensors.lithaTrack.crTrack("LandingPageView", {
        "page_name": "Magazine落地页",
        "refer_source": "活动页/Magazine",
        "campaign": 'SZSH_LITHA_LAUNCH-2023',
        "first_module_name": 'Magazine',
        "second_module_name": "点击阅览"
      })

      const that = this;
      const query = wx.createSelectorQuery()
      query.selectViewport().scrollOffset()
      query.exec(function(res){
        that.pageHeight = res[0] ? res[0]?.scrollHeight : 0
      })
      const device = wx.getSystemInfoSync()
      this.deviceHeight = device.screenHeight;
    },
    onHide() {
      // 神策埋点
      this.$commonSensors.lithaTrack.cTrack("PageLeave", {
        "page_name": "Magazine活动页",
        "campaign": 'SZSH_LITHA_LAUNCH-2023',
        "first_module_name": 'Magazine',
        "second_module_name": `点击阅览`,
        "view_progress": this.viewProgress
      })
    },
    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
      /**杂志首页页面滚动
       * @param {Object} e
       */
      onPageScroll(e) {
        let _num = (e.scrollTop + this.deviceHeight) / this.pageHeight;
        const _p = Number(_num.toFixed(1));
        if(_p > this.viewProgress) this.viewProgress = _p > 1 ? 1 : _p;

        let navbarHeight = getApp().globalData.navBarHeight;
        if (e.scrollTop > navbarHeight) {
          this.navbarData.whiteIcon = 0;
          this.navbarData.isTopFixed = false;
        } else {
          this.navbarData.whiteIcon = 1;
          this.navbarData.isTopFixed = true;
        }
      },
      /**杂志点击，跳转杂志详情页
       * @param {Object} e
       */
      handleMagazineDetails(e) {
        if (e.id && e.isOpen) {
          // 93号埋点-邂逅新生-Magazine页-点击阅读按钮
          const _clId = 'c_ebmp_draco_update_magazine_click_read';
          const _clParams = {
            campaign: 'SZSH_LITHA_LAUNCH-2023',
            c_event_category_1: 'browse',
            c_event_category_2: 'Magazine',
            c_click_area: 'button/点击阅读',
            c_content_name: '点击素材跳转至杂志内页',
            c_link_pagename: '杂志内页',
            c_link_path: '/pages/litha-launch/magazine/details?id=' + e.date
          };
          getApp().cl_tracker.track(_clId, _clParams);
          lithLaunch(_clId, _clParams)

          // 神策埋点
          this.$commonSensors.lithaTrack.cTrack("LandingPageOperation", {
            "page_name": "Magazine落地页",
            "campaign": 'SZSH_LITHA_LAUNCH-2023',
            "first_module_name": 'Magazine',
            "second_module_name": "点击阅览",
            "operation_type": "点击",
            "button_name": `VOL${e.id}点击阅读`
          })

          //  跳转杂志详情
          uni.navigateTo({
            url: '/pages/litha-launch/magazine/details?id=' + e.id
          });
        }
      },
      /**
       * magazine订阅按钮
       */
      async handleSubscribeMagazine() {
        let that = this
        // 92号埋点-邂逅新生-Magazine页-点击订阅按钮
        const _clId = 'c_ebmp_draco_update_magazine_click_subscribe';
        const _clParams = {
          campaign: 'SZSH_LITHA_LAUNCH-2023',
          c_event_category_1: 'subscribe',
          c_event_category_2: 'Magazine',
          c_click_area: 'button/订阅最新消息'
        };
        getApp().cl_tracker.track(_clId, _clParams);
        lithLaunch(_clId, _clParams)
        // 神策埋点
        this.$commonSensors.lithaTrack.cTrack("LandingPageOperation", {
          "page_name": "Magazine落地页",
          "campaign": 'SZSH_LITHA_LAUNCH-2023',
          "first_module_name": 'Magazine',
          "second_module_name": "点击阅览",
          "operation_type": "点击",
          "button_name": "订阅最新消息"
        })

        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || '';
        if (!!customerInfo.jwt) {
          let status = await util.getActivitySubscribeDetail(that.msgId, 'false', 'articleSubscribe');
          if (status.code === 1000) {
            let data = status.data;
            let state = data.state;
            let pageAfterSubscribe = data.pageAfterSubscribe || '';
            let templateId = data.templateId;
            if (state == 1) { //启用状态
              let SubscribeInfo = await util.getCustomerSubscribeInfo(that.msgId, templateId,
                pageAfterSubscribe, 'false', 'articleSubscribe')
              if (SubscribeInfo.code == 1000) { //已订阅
                this.handleShowTextToast('您已完成订阅')
                uni.setStorageSync('Subscribe', true)
                this.isSubscribe = true
              } else if (SubscribeInfo.code == -1010) { //未订阅
                uni.showModal({
                  title: '订阅一次以下消息通知',
                  content: '活动通知',
                  confirmText: "允许",
                  cancelText: "取消",
                  success: function(res) {
                    if (res.confirm) {
                      let tmplIds = [];
                      tmplIds.push(templateId)
                      that.$commonSensors.popupEvent('PopupExposure', {'popup_type' : '订阅消息', 'popup_name': '订阅消息弹窗', 'campaign': 'SZSH_LITHA_LAUNCH-2023'})
                      that.$commonSensors.modelAuthAsk('活动', tmplIds)
                      uni.requestSubscribeMessage({
                        tmplIds: tmplIds,
                        async success(res) {
                          if (res[templateId] == "accept") {
                            // 用户允许接收订阅消息
                            const result = await api.weixinSubscribe({
                              method: 'POST',
                              header: {
                                'jwt': customerInfo.jwt
                              },
                              query: {
                                "name": "活动模版消息",
                                "type": "活动消息",
                                "appId": getApp().globalData.app_id,
                                "openId": customerInfo.openId,
                                "params": {
                                  "activitySubscribeId": that.msgId,
                                }
                              }
                            });
                            if (result.code == 1000) {
                              that.handleShowTextToast('订阅成功')
                              uni.setStorageSync('Subscribe', true)
                              that.isSubscribe = true
                            } else {
                              that.handleShowTextToast('订阅失败')
                            }
                          }
                        },
                        fail(res) {
                          that.handleShowTextToast('订阅失败')
                        },
                        complete(res) {}
                      });
                    } else {
                      that.handleShowTextToast('订阅失败')
                    }
                  }
                })
              } else {
                that.handleShowTextToast(SubscribeInfo.msg)
              }
            } else {
              that.handleShowTextToast('活动已结束')
            }
          } else {
            that.handleShowTextToast('订阅失败')
          }
        } else {
          that.$refs.registerWidgetRef.openJoinMemberModal();
        }
      },

      onRegisterWidgetFinish() {
        const customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      },

      onShareAppMessage: async function(res) {
        let that = this
        let imageUrl = 'https://100000063-1252208446.file.myqcloud.com/images/litha/magazine/magazine-index.png'
        let path = '/pages/litha-launch/magazine/index'
        let title = '品读风味故事，卷起悠然时光。麦卡伦邀你阅见新生'
				this.$sr.setContext({ share_title: title || 'THE MACALLAN EBOUTIQUE麦卡伦' });
        return this.$commonFunction.commonShare(res, title, path, imageUrl)
      },
      onShareTimeline() {
				let title = '品读风味故事，卷起悠然时光。麦卡伦邀你阅见新生'
				this.$sr.setContext({ share_title: title || 'THE MACALLAN EBOUTIQUE麦卡伦' });
        return {
          title: title,
          query: '',
          imageUrl: 'https://100000063-1252208446.file.myqcloud.com/images/litha/magazine/magazine-index.png'
        };
      },
    }
  }
</script>

<style>
  .video_box {
    width: 100%;
    height: 1334rpx;
  }

  .magazine_title {
    width: 287rpx;
    height: 99rpx;
    margin: 50rpx auto 36rpx auto;
  }

  .subscribe_btn {
    width: 347rpx;
    height: 74rpx;
    margin: 0 auto;
  }

  .magazine_box {
    width: 100%;
    min-height: 877rpx;
    box-sizing: border-box;
    padding: 0 35rpx 90rpx 35rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }

  .arrow_bottom {
    width: 62rpx;
    height: 34rpx;
    margin: 40rpx auto 25rpx auto;
  }

  .list_1 {
    width: 680rpx;
    height: 877rpx;
    position: relative;
  }

  .drinking_tips {
    width: 246rpx;
    height: 16rpx;
    position: absolute;
    right: 0;
    bottom: -22rpx;
  }

  .list_item {
    width: 330rpx;
    height: 440rpx;
    margin-top: 40rpx;
  }
</style>
